package com.wyz.socket.core.base.frame.send;

import com.wyz.socket.core.base.IoArgs;
import com.wyz.socket.core.base.frame.Frame;
import com.wyz.socket.core.base.packet.AbstractSendPacket;

import java.io.IOException;
import java.nio.channels.ReadableByteChannel;

public class SendDirectEntityFrame extends AbstractSendPacketFrame {
    private final ReadableByteChannel channel;

    public SendDirectEntityFrame(int availabel, short identifier, AbstractSendPacket<?> sendPacket, ReadableByteChannel channel) {
        super(Math.min(availabel, Frame.MAX_CAPACITY), Frame.TYPE_ENTITY, Frame.FLAG_NON, identifier, sendPacket);
        this.channel = channel;
    }

    @Override
    protected Frame buildNextFrame() {
        int availabel = sendPacket.availabel();
        if (availabel <= 0) {
            return new CancelSendFrame(getBodyIdentifier());
        }
        return new SendDirectEntityFrame(availabel, getBodyIdentifier(), sendPacket, channel);
    }

    @Override
    protected int consumeBody(IoArgs args) throws IOException {
        if (sendPacket == null)
            return args.fillEmpty(bodyRemaining);
        return args.readFrom(channel);
    }
}
